package com.czhouse.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czhouse.mapper.TokenMapper;
import com.czhouse.mapper.UserMapper;
import com.czhouse.pojo.Token;
import com.czhouse.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TokenMapper tokenMapper;
    @Override
    public User selectUserByUsername(String userName) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username",userName);
        User user = userMapper.selectOne(qw);
        return user;
    }

    @Override
    public List<String> selectUserPermissions(Integer id) {
        List<String> list = userMapper.selectPermissionById(id);
        return list;
    }

    @Override
    public Boolean addUser(User user) {
        if (user.getUsername().length()>20||user.getUsername().length()<3||
                user.getPassword().length()>20||user.getPassword().length()<3){
            return false;
        }
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username",user.getUsername());
        User user1 = userMapper.selectOne(qw);
        if (user1!=null){
            return false;
        }
        byte[] bytes = user.getPassword().getBytes();
        String md5Password = DigestUtils.md5DigestAsHex(bytes);//加密工具类的方法
        user.setPassword(md5Password);
        userMapper.insert(user);
        return true;

    }

    @Override
    public String login(User user) {
        byte[] bytes = user.getPassword().getBytes();
        String md5Password = DigestUtils.md5DigestAsHex(bytes);//加密工具类的方法
        user.setPassword(md5Password);
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username",user.getUsername()).eq("password",md5Password);
        User user1 = userMapper.selectOne(qw);
        if (user1==null){
            return null;
        }
        String uuid = String.valueOf(UUID.randomUUID());
        Token token = new Token(null, uuid, user1.getId());
        QueryWrapper<Token> qw1 = new QueryWrapper<>();
        qw1.clear();
        qw1.eq("user_id",user1.getId());
        Token token1 = tokenMapper.selectOne(qw1);
        if (token1==null){
            tokenMapper.insert(token);
        }
        tokenMapper.update(token,null);
        return uuid;
    }
}
